import { supabase } from "./supabaseClient";
import authService from "./authService";

const supabaseService = {
    getSupabase() {
        return supabase;
    },
    async signUpOrIn(){
        const {data:signData, error:signError} = await supabaseService.signInWx();
        if (!signData.user){
            console.log("Sign in failed, try sign up");
            const {data:signUpData, error:signUpError} = await supabaseService.signUpWx();
            if (!signUpData.user){
                throw new Error("Sign up failed");
            } else {
                console.log("Sign up success:", signUpData.user);
            }
        } else {
            console.log("Sign in success:", signData.user);
        }
    },
    async signUpWx() {
        const user = authService.getUser();
        if (!user){
            throw new Error("User not found");
        }
        return await supabaseService.signUp(user.id + "@jishuba.cn", user.id.substring(0, 8));
    },
    async signInWx() {
        const user = authService.getUser();
        if (!user){
            throw new Error("User not found");
        }
        return await supabaseService.signIn(user.id + "@jishuba.cn", user.id.substring(0, 8));
    },
    async signUp (email: string, password: string) {
        try {
            const { data, error } = await supabase.auth.signUp({
                email,
                password,
            });
            return { data, error };
        } catch (error) {
            console.error("Error signing up:", error);
            throw error;
        }
    },
    async signIn (email: string, password: string) {
        try {
            const { data, error } = await supabase.auth.signInWithPassword({
                email,
                password,
            });
            console.log("supabase.auth.signInWithPassword result:", data);
            const result = await supabase.from('quiz_history').insert({
                "content": {"a": 1},
            });
            console.log("Upsert result:", result);
            return { data, error };
        } catch (error) {
            console.error("Error signing in:", error);
            throw error;
        }
    }
};
export default supabaseService;